<template>
  <div class="role-management">
    <div class="page-header">
      <h1 class="page-title">用户角色管理</h1>
      <p class="page-description">管理系统中的用户角色和权限分配</p>
    </div>

    <!-- 角色列表 -->
    <el-card class="roles-card">
      <template #header>
        <div class="card-header">
          <span>角色列表</span>
          <el-button 
            type="primary" 
            @click="showAddRoleDialog = true"
            v-permission="'user:manage'"
          >
            <el-icon><Plus /></el-icon>
            添加角色
          </el-button>
        </div>
      </template>

      <el-table :data="roles" style="width: 100%">
        <el-table-column prop="name" label="角色名称" width="150">
          <template #default="{ row }">
            <el-tag :type="getRoleTagType(row.key)">
              {{ row.name }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="描述" />
        
        <el-table-column prop="permissions" label="权限数量" width="120">
          <template #default="{ row }">
            <el-badge :value="row.permissions.length" type="primary" />
          </template>
        </el-table-column>
        
        <el-table-column prop="userCount" label="用户数量" width="120">
          <template #default="{ row }">
            <el-badge :value="getUserCountByRole(row.key)" type="success" />
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="editRole(row)"
              v-permission="'user:manage'"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteRole(row)"
              v-permission="'user:manage'"
              :disabled="isSystemRole(row.key)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="users-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户..."
              style="width: 200px; margin-right: 12px;"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button 
              type="primary" 
              @click="showAddUserDialog = true"
              v-permission="'user:manage'"
            >
              <el-icon><Plus /></el-icon>
              添加用户
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredUsers" style="width: 100%">
        <el-table-column prop="username" label="用户名" width="120" />
        
        <el-table-column prop="fullName" label="真实姓名" width="120" />
        
        <el-table-column prop="email" label="邮箱" width="200" />
        
        <el-table-column prop="role" label="角色" width="120">
          <template #default="{ row }">
            <el-tag :type="getRoleTagType(row.role)">
              {{ getRoleDisplayName(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'danger'">
              {{ row.status === 'ACTIVE' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="editUser(row)"
              v-permission="'user:manage'"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="changeUserRole(row)"
              v-permission="'user:manage'"
            >
              <el-icon><User /></el-icon>
              改角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      v-model="showAddRoleDialog"
      :title="editingRole ? '编辑角色' : '添加角色'"
      width="600px"
    >
      <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        
        <el-form-item label="角色标识" prop="key">
          <el-input v-model="roleForm.key" placeholder="请输入角色标识" :disabled="editingRole" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" placeholder="请输入角色描述" />
        </el-form-item>
        
        <el-form-item label="权限设置">
          <el-checkbox-group v-model="roleForm.permissions">
            <div class="permission-groups">
              <div v-for="group in permissionGroups" :key="group.name" class="permission-group">
                <h4>{{ group.name }}</h4>
                <el-checkbox
                  v-for="permission in group.permissions"
                  :key="permission.key"
                  :label="permission.key"
                >
                  {{ permission.name }}
                </el-checkbox>
              </div>
            </div>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddRoleDialog = false">取消</el-button>
        <el-button type="primary" @click="saveRole">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="showAddUserDialog"
      :title="editingUser ? '编辑用户' : '添加用户'"
      width="500px"
    >
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="editingUser" />
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="fullName">
          <el-input v-model="userForm.fullName" placeholder="请输入真实姓名" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="role in roles"
              :key="role.key"
              :label="role.name"
              :value="role.key"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="!editingUser" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio label="ACTIVE">正常</el-radio>
            <el-radio label="DISABLED">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddUserDialog = false">取消</el-button>
        <el-button type="primary" @click="saveUser">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改用户角色对话框 -->
    <el-dialog
      v-model="showChangeRoleDialog"
      title="修改用户角色"
      width="400px"
    >
      <el-form :model="changeRoleForm" ref="changeRoleFormRef" label-width="100px">
        <el-form-item label="用户名">
          <el-input :value="changeRoleForm.username" disabled />
        </el-form-item>
        
        <el-form-item label="当前角色">
          <el-tag :type="getRoleTagType(changeRoleForm.currentRole)">
            {{ getRoleDisplayName(changeRoleForm.currentRole) }}
          </el-tag>
        </el-form-item>
        
        <el-form-item label="新角色" prop="newRole">
          <el-select v-model="changeRoleForm.newRole" placeholder="请选择新角色" style="width: 100%">
            <el-option
              v-for="role in roles"
              :key="role.key"
              :label="role.name"
              :value="role.key"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showChangeRoleDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmChangeRole">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useAuthStore, PERMISSIONS, ROLES } from '../store/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Edit, 
  Delete, 
  Search, 
  User 
} from '@element-plus/icons-vue'

export default {
  name: 'RoleManagement',
  setup() {
    const authStore = useAuthStore()
    
    // 响应式数据
    const roles = ref([])
    const users = ref([])
    const searchKeyword = ref('')
    
    // 对话框状态
    const showAddRoleDialog = ref(false)
    const showAddUserDialog = ref(false)
    const showChangeRoleDialog = ref(false)
    
    // 编辑状态
    const editingRole = ref(null)
    const editingUser = ref(null)
    
    // 表单数据
    const roleForm = reactive({
      name: '',
      key: '',
      description: '',
      permissions: []
    })
    
    const userForm = reactive({
      username: '',
      fullName: '',
      email: '',
      role: '',
      password: '',
      status: 'ACTIVE'
    })
    
    const changeRoleForm = reactive({
      username: '',
      currentRole: '',
      newRole: ''
    })
    
    // 权限分组
    const permissionGroups = [
      {
        name: '工单管理',
        permissions: [
          { key: PERMISSIONS.TICKET_READ, name: '查看工单' },
          { key: PERMISSIONS.TICKET_CREATE, name: '创建工单' },
          { key: PERMISSIONS.TICKET_UPDATE, name: '更新工单' },
          { key: PERMISSIONS.TICKET_DELETE, name: '删除工单' },
          { key: PERMISSIONS.TICKET_ASSIGN, name: '分配工单' }
        ]
      },
      {
        name: '用户管理',
        permissions: [
          { key: PERMISSIONS.USER_MANAGE, name: '用户管理' }
        ]
      },
      {
        name: '系统管理',
        permissions: [
          { key: PERMISSIONS.SYSTEM_CONFIG, name: '系统配置' }
        ]
      },
      {
        name: '报表管理',
        permissions: [
          { key: PERMISSIONS.REPORT_VIEW, name: '查看报表' }
        ]
      },
      {
        name: '通知管理',
        permissions: [
          { key: PERMISSIONS.NOTIFICATION_MANAGE, name: '通知管理' },
          { key: PERMISSIONS.NOTIFICATION_SEND, name: '发送通知' }
        ]
      },
      {
        name: '文件管理',
        permissions: [
          { key: PERMISSIONS.FILE_UPLOAD, name: '上传文件' },
          { key: PERMISSIONS.FILE_DELETE, name: '删除文件' },
          { key: PERMISSIONS.FILE_MANAGE, name: '文件管理' }
        ]
      }
    ]
    
    // 表单验证规则
    const roleRules = {
      name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' }
      ],
      key: [
        { required: true, message: '请输入角色标识', trigger: 'blur' }
      ]
    }
    
    const userRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      fullName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度至少6位', trigger: 'blur' }
      ]
    }
    
    // 计算属性
    const filteredUsers = computed(() => {
      if (!searchKeyword.value) return users.value
      return users.value.filter(user => 
        user.username.includes(searchKeyword.value) ||
        user.fullName.includes(searchKeyword.value) ||
        user.email.includes(searchKeyword.value)
      )
    })
    
    // 方法
    const getRoleTagType = (roleKey) => {
      const roleTypes = {
        admin: 'danger',
        manager: 'warning',
        agent: 'success',
        customer: 'info'
      }
      return roleTypes[roleKey] || 'info'
    }
    
    const getRoleDisplayName = (roleKey) => {
      const roleNames = {
        admin: '系统管理员',
        manager: '管理员',
        agent: '客服',
        customer: '客户'
      }
      return roleNames[roleKey] || roleKey
    }
    
    const getUserCountByRole = (roleKey) => {
      return users.value.filter(user => user.role === roleKey).length
    }
    
    const isSystemRole = (roleKey) => {
      return ['admin', 'customer'].includes(roleKey)
    }
    
    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleString('zh-CN')
    }
    
    const loadRoles = () => {
      // 模拟角色数据
      roles.value = [
        {
          key: 'admin',
          name: '系统管理员',
          description: '拥有系统所有权限',
          permissions: Object.values(PERMISSIONS)
        },
        {
          key: 'manager',
          name: '管理员',
          description: '拥有大部分管理权限',
          permissions: [
            PERMISSIONS.TICKET_READ,
            PERMISSIONS.TICKET_CREATE,
            PERMISSIONS.TICKET_UPDATE,
            PERMISSIONS.TICKET_ASSIGN,
            PERMISSIONS.USER_MANAGE,
            PERMISSIONS.REPORT_VIEW,
            PERMISSIONS.NOTIFICATION_MANAGE,
            PERMISSIONS.NOTIFICATION_SEND,
            PERMISSIONS.FILE_UPLOAD,
            PERMISSIONS.FILE_DELETE,
            PERMISSIONS.FILE_MANAGE
          ]
        },
        {
          key: 'agent',
          name: '客服',
          description: '处理客户工单',
          permissions: [
            PERMISSIONS.TICKET_READ,
            PERMISSIONS.TICKET_CREATE,
            PERMISSIONS.TICKET_UPDATE,
            PERMISSIONS.TICKET_ASSIGN,
            PERMISSIONS.REPORT_VIEW,
            PERMISSIONS.NOTIFICATION_SEND,
            PERMISSIONS.FILE_UPLOAD
          ]
        },
        {
          key: 'customer',
          name: '客户',
          description: '提交和查看工单',
          permissions: [
            PERMISSIONS.TICKET_READ,
            PERMISSIONS.TICKET_CREATE
          ]
        }
      ]
    }
    
    const loadUsers = () => {
      // 模拟用户数据
      users.value = [
        {
          id: 1,
          username: 'admin',
          fullName: '系统管理员',
          email: 'admin@example.com',
          role: 'admin',
          status: 'ACTIVE',
          createdAt: '2024-01-01T00:00:00Z'
        },
        {
          id: 2,
          username: 'manager1',
          fullName: '张经理',
          email: 'manager1@example.com',
          role: 'manager',
          status: 'ACTIVE',
          createdAt: '2024-01-02T00:00:00Z'
        },
        {
          id: 3,
          username: 'agent1',
          fullName: '李客服',
          email: 'agent1@example.com',
          role: 'agent',
          status: 'ACTIVE',
          createdAt: '2024-01-03T00:00:00Z'
        },
        {
          id: 4,
          username: 'customer1',
          fullName: '王客户',
          email: 'customer1@example.com',
          role: 'customer',
          status: 'ACTIVE',
          createdAt: '2024-01-04T00:00:00Z'
        }
      ]
    }
    
    const editRole = (role) => {
      editingRole.value = role
      Object.assign(roleForm, {
        name: role.name,
        key: role.key,
        description: role.description,
        permissions: [...role.permissions]
      })
      showAddRoleDialog.value = true
    }
    
    const deleteRole = async (role) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除角色"${role.name}"吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 模拟删除
        const index = roles.value.findIndex(r => r.key === role.key)
        if (index > -1) {
          roles.value.splice(index, 1)
          ElMessage.success('角色删除成功')
        }
      } catch (error) {
        // 用户取消
      }
    }
    
    const saveRole = () => {
      if (editingRole.value) {
        // 编辑角色
        const index = roles.value.findIndex(r => r.key === editingRole.value.key)
        if (index > -1) {
          roles.value[index] = {
            ...roles.value[index],
            name: roleForm.name,
            description: roleForm.description,
            permissions: [...roleForm.permissions]
          }
          ElMessage.success('角色更新成功')
        }
      } else {
        // 添加角色
        roles.value.push({
          key: roleForm.key,
          name: roleForm.name,
          description: roleForm.description,
          permissions: [...roleForm.permissions]
        })
        ElMessage.success('角色添加成功')
      }
      
      showAddRoleDialog.value = false
      resetRoleForm()
    }
    
    const editUser = (user) => {
      editingUser.value = user
      Object.assign(userForm, {
        username: user.username,
        fullName: user.fullName,
        email: user.email,
        role: user.role,
        status: user.status
      })
      showAddUserDialog.value = true
    }
    
    const saveUser = () => {
      if (editingUser.value) {
        // 编辑用户
        const index = users.value.findIndex(u => u.id === editingUser.value.id)
        if (index > -1) {
          users.value[index] = {
            ...users.value[index],
            fullName: userForm.fullName,
            email: userForm.email,
            role: userForm.role,
            status: userForm.status
          }
          ElMessage.success('用户更新成功')
        }
      } else {
        // 添加用户
        const newUser = {
          id: Date.now(),
          username: userForm.username,
          fullName: userForm.fullName,
          email: userForm.email,
          role: userForm.role,
          status: userForm.status,
          createdAt: new Date().toISOString()
        }
        users.value.push(newUser)
        ElMessage.success('用户添加成功')
      }
      
      showAddUserDialog.value = false
      resetUserForm()
    }
    
    const changeUserRole = (user) => {
      Object.assign(changeRoleForm, {
        username: user.username,
        currentRole: user.role,
        newRole: user.role
      })
      showChangeRoleDialog.value = true
    }
    
    const confirmChangeRole = () => {
      const user = users.value.find(u => u.username === changeRoleForm.username)
      if (user) {
        user.role = changeRoleForm.newRole
        ElMessage.success('用户角色修改成功')
      }
      showChangeRoleDialog.value = false
    }
    
    const resetRoleForm = () => {
      Object.assign(roleForm, {
        name: '',
        key: '',
        description: '',
        permissions: []
      })
      editingRole.value = null
    }
    
    const resetUserForm = () => {
      Object.assign(userForm, {
        username: '',
        fullName: '',
        email: '',
        role: '',
        password: '',
        status: 'ACTIVE'
      })
      editingUser.value = null
    }
    
    // 生命周期
    onMounted(() => {
      loadRoles()
      loadUsers()
    })
    
    return {
      roles,
      users,
      searchKeyword,
      filteredUsers,
      showAddRoleDialog,
      showAddUserDialog,
      showChangeRoleDialog,
      editingRole,
      editingUser,
      roleForm,
      userForm,
      changeRoleForm,
      permissionGroups,
      roleRules,
      userRules,
      getRoleTagType,
      getRoleDisplayName,
      getUserCountByRole,
      isSystemRole,
      formatDate,
      editRole,
      deleteRole,
      saveRole,
      editUser,
      saveUser,
      changeUserRole,
      confirmChangeRole
    }
  }
}
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 8px 0;
}

.page-description {
  font-size: 16px;
  color: var(--text-secondary);
  margin: 0;
}

.roles-card,
.users-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: var(--text-primary);
}

.header-actions {
  display: flex;
  align-items: center;
}

.permission-groups {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  max-height: 300px;
  overflow-y: auto;
  padding: 16px;
  border: 1px solid var(--border-primary);
  border-radius: 8px;
  background-color: var(--bg-secondary);
}

.permission-group h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary);
  border-bottom: 1px solid var(--border-primary);
  padding-bottom: 8px;
}

.permission-group .el-checkbox {
  display: block;
  margin-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .role-management {
    padding: 16px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .permission-groups {
    grid-template-columns: 1fr;
    max-height: 200px;
  }
}

/* 暗色主题适配 */
.dark .permission-groups {
  background-color: var(--bg-tertiary);
  border-color: var(--border-primary);
}
</style>
